package com.ptswitch.material.service.impl;

import java.util.Collection;

import org.hxzon.project.AbstractModelService;
import org.hxzon.util.StringUtil;
import org.hxzon.util.cache.FifoCache;
import org.springframework.stereotype.Service;

import com.ptswitch.material.model.common.LoginInfo;
import com.ptswitch.material.model.common.Uzer;
import com.ptswitch.material.service.LoginInfoService;

@Service
public class LoginInfoServiceImpl implements LoginInfoService {
    private FifoCache<String, LoginInfo> loginInfoCache = new FifoCache<String, LoginInfo>(100);

    public void save(LoginInfo user) {
        //super.save(user);
        loginInfoCache.add(user.getUsername(), user);
    }

    public void saveAll(Collection<LoginInfo> users) {
        for (LoginInfo user : users) {
            save(user);
        }
    }

    public void delete(LoginInfo user) {
        //super.delete(user);
        loginInfoCache.remove(user.getUsername());
    }

    public LoginInfo findById(String id) {
        LoginInfo result = null;//super.findById(id);
        if (result != null) {
            loginInfoCache.add(result.getUsername(), result);
        }
        return result;
    }

    public void deleteByUsername(String username) {
        //dao.execute("delete LoginInfo p where p.username='" + username + "'");
        loginInfoCache.remove(username);
    }

    public LoginInfo findByUsername(String username) {
        if (username == null || username.isEmpty()) {
            return null;
        }
        if (Uzer.Username_Guess.equals(username)) {
            return null;//return null not return new Uzer()
        }
        LoginInfo result = loginInfoCache.get(username);
        if (result != null) {
            return result;
        }
        username = StringUtil.escapeSql(username);
        result = null;//dao.findOne(LoginInfo.class, " where p.username='" + username + "'");
        if (result != null) {
            loginInfoCache.add(result.getUsername(), result);
        }
        return result;
    }

    public LoginInfo findByUsernameAndLoginToken(String username, String loginToken) {
        if (username == null || username.isEmpty() || loginToken == null || loginToken.isEmpty()) {
            return null;
        }
        LoginInfo result = findByUsername(username);
        if (result != null) {
            if (loginToken.equals(result.getId())) {
                return result;
            }
        }
        return null;
    }

}
